﻿// COPYRIGHT (C) Markeluo ALL RIGHTS RESERVED. 
// GITEE: https://gitee.com/luowanli/AntdUI 
// QQ: 563944808

using Furion;
using IMES.BLL;
using IMES.Entity;
using IMES.Utils;
using IMES.VO;
using Mapster;

namespace IMES.Page.SysRoleUser
{
    public partial class frm_RoleEditor : AntdUI.Window, IFormLoader
    {
        private SysRoleVO? _model;
        RoleRep rep= App.GetService<RoleRep>();
        private bool isAdd = true;
        public frm_RoleEditor()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 编辑对象
        /// </summary>
        public SysRoleVO? EditModel
        {
            get { return _model; }
        }

        public bool InitData(object[] args)
        {
            if (args != null && args.Length > 0 && args[0] is SysRoleVO) {
                _model = (SysRoleVO)args[0];
            }

            BindControl();
            return true;
        }

        private void BindControl()
        {
            if (_model == null) return;
            txtRoleName.Text = _model.Name;
            txtRemark.Text = _model.Remark;
            switchUsable.Checked = (bool)_model.Usable!;
            switchIsAdmin.Checked = _model.IsAdmin;
            pgHeader.Text = "角色编辑";
            isAdd = false;
        }

        private bool ValidateData()
        {
            bool bolNext = true;
            if (_model == null) _model = new SysRoleVO();
            _model.Name = txtRoleName.Text;
            _model.Remark = txtRemark.Text;
            _model.Usable = switchUsable.Checked;
            _model.IsAdmin = switchIsAdmin.Checked;
            if (string.IsNullOrEmpty(_model.Name))
            {
                showWarning(AntdUI.TType.Warn,"角色名称不能为空!");
                bolNext = false;
            }
            return bolNext;
        }
        private void showWarning(AntdUI.TType type,string txt)
        {
            tipTxt.Icon = type;
            tipTxt.Text= txt;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //验证数据
            bool isNext= ValidateData();
            if (!isNext) return;
            if (_model!.Id > 0)
            {
                //编辑
                rep.Update(_model.Adapt<Role>());
            }
            else
            {
                //新增
                var temp=new Role() {Name=_model.Name,IsAdmin=_model.IsAdmin,Usable=_model.Usable,Remark=_model.Remark};
                rep.Insert(temp);
                _model = temp.Adapt<SysRoleVO>();
            }
            this.DialogResult = DialogResult.OK;
        }
    }
}
